<?php
/**
 * 继承 KartikActionColumn 的部分方法，并修改一下
 * User: crstu
 * Date: 2016/5/26
 * Time: 16:53
 */

namespace common\widgets;


use kartik\grid\ActionColumn;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class KartikActionColumn extends ActionColumn
{

    //单元格表头
    public $header = "操作";

    //项目操作
    /*
     * 可操作项目数组
     * [$title, $url, $class, $options]
     * [标题, 链接, 样式, 选项]
     * $options = [
     *  'pk' => 主键名称
     *  'display' => 是否显示的条件
     * ];
     */
    public $items = [];

    //单元格宽度（父类默认为80px，这里取消这个设置）
    public $width = '';


    //渲染
    protected function renderDataCellContent($model, $key, $index)
    {
        $content = '';
        if(!empty($this->items) || is_array($this->items)){
            foreach ($this->items as $v){
                $pk = 'id';
                $display = true;
                if(isset($v[3])){
                    $options = $v[3];
                    if(isset($options['pk']) && !empty($options['pk'])) $pk = $options['pk'];
                    //分析显示条件
                    if(isset($options['display']) && !empty($options['display']) && is_array($options['display'])){
                        $attribute = $options['display'][0];
                        $operation = $options['display'][1];
                        $other     = $options['display'][2];
                        $value     = $model->$attribute;
                        if($operation == '>'){
                            $display = boolval($value > $other);
                        }elseif ($operation == '>='){
                            $display = boolval($value >= $other);
                        }elseif ($operation == '<'){
                            $display = boolval($value < $other);
                        }elseif ($operation == '<='){
                            $display = boolval($value <= $other);
                        }elseif ($operation == '=='){
                            $display = boolval($value == $other);
                        }elseif ($operation == '!='){
                            $display = boolval($value != $other);
                        }else{
                            $display = boolval($value);
                        }
                    }
                }

                if($display){
                    $class = isset($v[2]) ? $v[2] : 'btn-default';
                    $content .= Html::a($v[0], Url::to([$v[1], $pk => $model->id]), ['class'=>'btn btn-xs '.$class]) .'&nbsp;';
                }
            }
        }
        return trim($content);
    }


    /**
     * @inheritdoc
     */
    public function renderDataCell($model, $key, $index)
    {
        $options = $this->fetchContentOptions($model, $key, $index);
        return Html::tag('td', $this->renderDataCellContent($model, $key, $index), $options);
    }

}